<script setup lang="ts">
import { onMounted, ref, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from "../request/request";

import { useUsersStore } from "../store/user";
const store = useUsersStore();


const route = useRoute()
const router = useRouter()

store.$onAction(
  ({
    name, // action 名称
    store, // store 实例，类似 `someStore`
    args, // 传递给 action 的参数数组
    after, // 在 action 返回或解决后的钩子
    onError, // action 抛出或拒绝的钩子
  }) => {
    // 为这个特定的 action 调用提供一个共享变量
    const startTime = Date.now()
    // 这将在执行 "store "的 action 之前触发。
    console.log(`Start "${name}" with params [${args.join(', ')}].`)

    if (name == 'changeKeywordsEvent') {
      // 此事件由搜索框触发，说明用户输入了关键词并需要搜索，则需要请求后端获取搜索结果
      console.log('Keywords changed need refresh result view');
      window.scrollTo(0, 0)
      store.newsSearchResultViewScrollPosition = 0
      store.newsSearchResult = []
      getContents()
    }
    // 这将在 action 成功并完全运行后触发。
    // 它等待着任何返回的 promise
    after((result) => {
      console.log(
        `Finished "${name}" after ${Date.now() - startTime
        }ms.\nResult: ${result}.`
      )
    })

    // 如果 action 抛出或返回一个拒绝的 promise，这将触发
    onError((error) => {
      console.warn(
        `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
      )
    })
  }
)


const resultLoading = ref(true)

const result = ref([{
  "id": 0,
  "title": "",
  "passageContent": "",
  "postTime": "",
  "viewNum": 0,
  "commentNum": 0
}])


const getContents = () => {

  resultLoading.value = true
  console.log('in news search result getContents');
  console.log(route.params);
  console.log(store.keywords);

  request.get("/news/search/" + store.keywords).then((response) => {
    console.log(response);
    result.value = response.data
    if (response.data != "" && response.data.length != 0) {
      result.value = response.data
    }

    store.newsSearchResult = response.data
    resultLoading.value = false
  })
}

onMounted(() => {
  window.scrollTo(0, 0)

  // 有时候是从路由直接进来的，则需要设置pinia里面的keywords
  store.keywords = route.params.keywords as string

  console.log('result view mounted');

  getContents()
})

onActivated(() => {
  // keep alive下，页面被激活都会触发这里，以下是三种进入情况
  // 从url直接进入，经过测试，必然是触发mount，所以可以在mount里面提前设置
  // 从搜索框搜索进入，pinia事件会比这个早触发，所以可以在pinia监听里面提前设置
  // 从newView返回，无论怎样，都不希望ScrollPosition变化
  // 因此这里直接写为从ScrollPosition取得数据然后设置给window就好
  console.log('in actived');
  
  console.log(store.newsSearchResultViewScrollPosition);
  window.scrollTo(0, store.newsSearchResultViewScrollPosition)
  
  if (store.needForceRefresh) {
    // 说明出现了like or dislike行为，则需要刷新
    console.log('need refresh');
    getContents()
    // 只有主页能设这个量为false
  }
})

const gotoNewsView = (newsId: number) => {
  console.log(document.documentElement.scrollTop)
  store.newsSearchResultViewScrollPosition = document.documentElement.scrollTop
  router.push({
    path: '/news/' + newsId,
  })
}


const gotoHome = () => {
  // 利用pinia全局把keywords更改掉了
  store.keywords = ''
  router.push("/")
  // router.replace("/")

}
</script>


<template>
  <div class="main" ref="scrollRef" >

    <div v-loading="resultLoading" class="index_content">

      <div>
        <el-button @click="gotoHome()" type="success" style="display: inline; float: right; margin-top: 10px;"> 返回
        </el-button>

      </div>

      <div class="">
        <p class="">找到<span> {{ result.length }}</span>个结果</p>
      </div>

      <div>
        <div class="index_searchresult" id="scroller">
          <ul>

            <li v-for="(item) in result">
              <div class="mdCard"><a @click="gotoNewsView(item.id)">
                  <h2>{{ item.title }}</h2>
                </a>
                <p> {{ item.passageContent.substring(0, 20) }} …</p>
                <p><span> {{ item.postTime.substring(0, 10) }}} </span><span>兴趣数量 {{ item.viewNum }}</span></p>
              </div>
            </li>


          </ul>
        </div>
      </div>

    </div>

    <el-backtop :right="100" :bottom="100" />





  </div>
</template>

<style scoped>
.main {
  /* padding-top: 74px; */

  padding: 80px 5vw 80px 5vw;
  padding-top: 82px !important;
  padding-bottom: 80px !important;
  /* min-height: 73vh; */
}

.title {
  font-size: 32px;
  font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
  font-weight: 700;
  color: #000;
  line-height: 42px;
}

.sub {
  display: flex;
  -moz-box-pack: justify;
  justify-content: space-between;
  -moz-box-align: center;
  align-items: center;
  margin: 20px 0 20px;
  font-size: 12px;
  font-family: MicrosoftYaHei;
  color: #999;
  line-height: 18px;
  margin-right: 10px;
}

.content {
  font-family: MicrosoftYaHei;
  color: #333;
  margin: 0 auto;
  line-height: 30px;
  letter-spacing: .5px;
  word-wrap: break-word;
  font-size: 16px;
}

p {
  display: block;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
}

.index_content {
  background: #fff;
  padding: 30px;
}

.index_content .index_searchresult ul li {
  padding: 20px 0;
  border-bottom: 1px solid #d7d7d7;
}

a {
  color: #00a5eb;
  text-decoration: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  transition: color .3s;
  -webkit-text-decoration-skip: objects;
}

li,
ul {
  list-style: none;
  padding-inline-start: 0px;
}

.index_content .index_searchresult ul li h2 {
  line-height: 24px;
  color: #4c4c4c;
  font-size: 18px;
  cursor: pointer;
}

.index_content .index_searchresult ul li p:last-child {
  text-align: right;
  margin-bottom: 0;
  color: #a0a0a0;
}


.index_content .index_searchresult ul li p {
  line-height: 24px;
  margin-top: 12px;
  color: #666;
  font-size: 12px;
}

.index_content .index_searchresult ul li p:last-child span {
  padding: 0 10px;
  border-right: 1px solid #eee;
}
</style>
